﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using EngineOfEvermore.Common;

namespace EngineOfEvermore.Scene.Visual
{
    enum RectangleContainerProxyType
    {
        BEGIN,
        END
    }

    class RectangleContainerXProxy : IComparable<RectangleContainerXProxy>
    {
        public RectangleContainerXProxy( Drawable item, 
            RectangleContainerProxyType type,
            int flagIndex )
        {
            this.Item = item;
            this.Type = type;
            this.QueryKeyIndex = flagIndex;
        }

        public readonly RectangleBounded Item;
        public readonly RectangleContainerProxyType Type;
        public readonly int QueryKeyIndex;

        public float RefValue
        {
            get
            {
                return ( this.Type == RectangleContainerProxyType.BEGIN ) ?
                    this.Item.AABB.Left : this.Item.AABB.Right;
            }
        }

        public int CompareTo( RectangleContainerXProxy other )
        {
            float thisValue = this.RefValue;
            float otherValue = other.RefValue;

            return thisValue < otherValue ? -1 : ( thisValue > otherValue ? 1 : 0 );
        }
    }

    class RectangleContainerYProxy : IComparable<RectangleContainerYProxy>
    {
        public RectangleContainerYProxy( Drawable item, 
            RectangleContainerProxyType type,
            int flagIndex )
        {
            this.Item = item;
            this.Type = type;
            this.QueryKeyIndex = flagIndex;
        }

        public readonly RectangleBounded Item;
        public readonly RectangleContainerProxyType Type;
        public readonly int QueryKeyIndex;

        public float RefValue
        {
            get
            {
                return ( this.Type == RectangleContainerProxyType.BEGIN ) ?
                    this.Item.AABB.Left : this.Item.AABB.Right;
            }
        }

        public int CompareTo( RectangleContainerYProxy other )
        {
            float thisValue = this.RefValue;
            float otherValue = other.RefValue;

            return thisValue < otherValue ? -1 : ( thisValue > otherValue ? 1 : 0 );
        }
    }

    class RectangleContainer
    {
        LinkedList<RectangleContainerXProxy> _xProxyList = 
            new LinkedList<RectangleContainerXProxy>();
        LinkedList<RectangleContainerYProxy> _yProxyList = 
            new LinkedList<RectangleContainerYProxy>();

        List<uint> _proxyQueryKeys = new List<uint>();
        List<int> _freeQueryKeyIndices = new List<int>();
        uint _queryKey;

        public RectangleContainer()
        {
            for ( int i = 0; i < 32; ++i )
            {
                _proxyQueryKeys.Add( 0 );
                _freeQueryKeyIndices.Add( i );
            }
        }

        int _getQueryKeyIndex()
        {
            if ( _freeQueryKeyIndices.Count == 0 )
            {
                int start = _proxyQueryKeys.Count;

                for ( int i = 0; i < 32; ++i )
                {
                    _proxyQueryKeys.Add( _queryKey );
                    _freeQueryKeyIndices.Add( start + i );
                }
            }

            int index = _freeQueryKeyIndices[_freeQueryKeyIndices.Count - 1];
            _freeQueryKeyIndices.RemoveAt( _freeQueryKeyIndices.Count - 1 );
            return index;
        }

        public void RegisterItem( Drawable item )
        {
            Debug.Assert( !_xProxyList.Any( proxy => proxy.Item == item ) );
            Debug.Assert( !_yProxyList.Any( proxy => proxy.Item == item ) );

            int flagIndex = _getQueryKeyIndex();

            RectangleContainerXProxy beginXProxy = 
                new RectangleContainerXProxy( item, 
                    RectangleContainerProxyType.BEGIN, 
                    flagIndex );

            RectangleContainerXProxy endXProxy = 
                new RectangleContainerXProxy( item, 
                    RectangleContainerProxyType.END, 
                    flagIndex );

            if ( _xProxyList.First != null )
            {
                LinkedListNode<RectangleContainerXProxy> it = _xProxyList.First;
                
                while ( it != null && it.Value.RefValue < beginXProxy.RefValue )
                {
                    it = it.Next;
                }

                if ( it != null )
                {
                    item.ContainerBeginXProxy = 
                        _xProxyList.AddBefore( it, beginXProxy );

                    while ( it != null && it.Value.RefValue < endXProxy.RefValue )
                    {
                        it = it.Next;
                    }

                    if ( it != null )
                    {
                        _xProxyList.AddBefore( it, endXProxy );
                    }
                    else
                    {
                        _xProxyList.AddLast( endXProxy );
                    }
                }
                else
                {
                    item.ContainerBeginXProxy = _xProxyList.AddLast( beginXProxy );
                    _xProxyList.AddLast( endXProxy );
                }
            }
            else
            {
                _xProxyList.AddFirst( endXProxy );
                item.ContainerBeginXProxy = _xProxyList.AddFirst( beginXProxy );
            }

            RectangleContainerYProxy beginYProxy = 
                new RectangleContainerYProxy( item, 
                    RectangleContainerProxyType.BEGIN,
                    flagIndex 
                    );

            RectangleContainerYProxy endYProxy = 
                new RectangleContainerYProxy( item, 
                    RectangleContainerProxyType.END, 
                    flagIndex );

            if ( _yProxyList.First != null )
            {
                LinkedListNode<RectangleContainerYProxy> it = _yProxyList.First;

                while ( it != null && it.Value.RefValue < beginYProxy.RefValue )
                {
                    it = it.Next;
                }

                if ( it != null )
                {
                    item.ContainerBeginYProxy = 
                        _yProxyList.AddBefore( it, beginYProxy );

                    while ( it != null && it.Value.RefValue < endYProxy.RefValue )
                    {
                        it = it.Next;
                    }

                    if ( it != null )
                    {
                        _yProxyList.AddBefore( it, endYProxy );
                    }
                    else
                    {
                        _yProxyList.AddLast( endYProxy );
                    }
                }
                else
                {
                    item.ContainerBeginYProxy = _yProxyList.AddLast( beginYProxy );
                    _yProxyList.AddLast( endYProxy );
                }
            }
            else
            {
                _yProxyList.AddFirst( endYProxy );
                item.ContainerBeginYProxy = _yProxyList.AddFirst( beginYProxy );
            }

            Debug.Assert( item.ContainerBeginXProxy.Value.Type == RectangleContainerProxyType.BEGIN );
            Debug.Assert( item.ContainerBeginYProxy.Value.Type == RectangleContainerProxyType.BEGIN );
        }

        public void UnregisterItem( Drawable item )
        {
            Debug.Assert( _xProxyList.Count( proxy => proxy.Item == item ) == 2 );
            Debug.Assert( _yProxyList.Count( proxy => proxy.Item == item ) == 2 );

            LinkedListNode<RectangleContainerXProxy> xIt = _xProxyList.First;

            while ( xIt != null )
            {
                if ( xIt.Value.Item == item )
                {
                    LinkedListNode<RectangleContainerXProxy> deletedNode = xIt;
                    xIt = xIt.Next;
                    _xProxyList.Remove( deletedNode );
                }
                else
                {
                    xIt = xIt.Next;
                }
            }

            LinkedListNode<RectangleContainerYProxy> yIt = _yProxyList.First;

            while ( yIt != null )
            {
                if ( yIt.Value.Item == item )
                {
                    LinkedListNode<RectangleContainerYProxy> deletedNode = yIt;
                    yIt = yIt.Next;
                    _yProxyList.Remove( deletedNode );
                }
                else
                {
                    yIt = yIt.Next;
                }
            }

            item.ContainerBeginXProxy = null;
            item.ContainerBeginYProxy = null;
        }

        public void Update()
        {
            _xProxyList.InsertionSort();
            _yProxyList.InsertionSort();
        }

        public void FindOverlaps( RectangleBounded item, 
            ICollection<RectangleBounded> output )
        {
            Debug.Assert( _xProxyList.Count( proxy => proxy.Item == item ) == 2 );
            Debug.Assert( _yProxyList.Count( proxy => proxy.Item == item ) == 2 );

            ++_queryKey;

            LinkedListNode<RectangleContainerXProxy> xIt = 
                item.ContainerBeginXProxy.Next;

            while ( xIt.Value.Item != item )
            {
                _proxyQueryKeys[xIt.Value.QueryKeyIndex] = _queryKey;
            }

            LinkedListNode<RectangleContainerYProxy> yIt =
                item.ContainerBeginYProxy.Next;

            while ( yIt.Value.Item != item )
            {
                if ( _proxyQueryKeys[yIt.Value.QueryKeyIndex] == _queryKey )
                {
                    output.Add( yIt.Value.Item );
                }
            }
        }
    }
}
